package edu.uic.ids517.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import edu.uic.ids517.model.CreateTableBean;
import edu.uic.ids517.model.DatabaseAccessBean;

public class CreateTableServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 

		System.out.println("CreateTableServlet");
		String nextUrl = "/dbAccess.jsp";
		String failureUrl = "/Error.jsp";	
		HttpSession session = request.getSession();

		String tableName = request.getParameter("tableName");
		String column1 = request.getParameter("column1");
		String dataType1 = request.getParameter("dataType1");	
		String column2 = request.getParameter("column2");
		String dataType2 = request.getParameter("dataType2");	
		String column3 = request.getParameter("column3");
		String dataType3 =	request.getParameter("dataType3");			

		if(tableName.length() == 0 || column1.length() == 0 || dataType1.length() == 0 || column2.length() == 0 || dataType2.length() == 0 || column3.length() == 0 || dataType3.length() == 0){
			RequestDispatcher dispatcher = request.getRequestDispatcher(failureUrl);
			request.setAttribute("errorMessage", "Table Creation Failure: All fields are mandatory!");
			dispatcher.forward(request, response); 
		}

		/***   DB Access Bean  ****/
		DatabaseAccessBean dbase = (DatabaseAccessBean) session.getAttribute("dbaseBean");
		CreateTableBean createTable = (CreateTableBean) session.getAttribute("createTableBean");		
		createTable.setTableName(tableName);				
		createTable.setColumn1(column1);
		createTable.setDataType1(dataType1);
		createTable.setColumn2(column2);
		createTable.setDataType2(dataType2);
		createTable.setColumn3(column3);
		createTable.setDataType3(dataType3);		

		dbase.setCreateBean(createTable);
		int result = dbase.executeCreateSQL();
		if(result != 0){
			System.out.println("SUCCESS: TABLE CRETATED");
		}
		request.setAttribute("message", "Table created!");
		RequestDispatcher dispatcher = request.getRequestDispatcher(nextUrl); 
		dispatcher.forward(request, response); 		
	}

}
